package com.songcha.sakura.mvvm.home.cate

import com.google.gson.Gson
import com.songcha.library_base.mvvm.base.BaseRepository
import com.songcha.sakura.bean.ComicListBean
import com.songcha.sakura.config.BaseConfig
import com.songcha.sakura.util.UrlUtil
import com.songcha.library_database_sakura.greendao.GreenDaoManager
import io.reactivex.Observable
import org.jsoup.Jsoup

class HomeCateRepository : BaseRepository()  {

    fun getComicListByDb(index:Int): Observable<ComicListBean> {
        return createObservable {
            val homeCacheDao= GreenDaoManager.getInstance().homeCacheDao
            val list=homeCacheDao.loadAll()

            if(list.size>0){
                val homeCacheBean=list[0]
                var bean=ComicListBean()
                if(index==1){
                    bean= Gson().fromJson(homeCacheBean.warmBlood,ComicListBean::class.java)
                }else if(index==2){
                    bean= Gson().fromJson(homeCacheBean.fight,ComicListBean::class.java)
                }

                it.onNext(bean)
                it.onComplete()

            }
        }
    }



    fun getComicList(title:String,page:Int): Observable<ComicListBean> {
        return createNetworkObservable {
            val data=mutableListOf<ComicListBean.ComicBean>()

            var t=title
            if(t.isNotEmpty()){
                t=UrlUtil.urlEncoded(t)
            }

            //http://www.dmh8.com/list/2_$page.html
            val document=Jsoup.connect("${BaseConfig.BASE_URL}/so.asp?id=2&page=$page&gj=$t&pl=time").get()

            val elements=document.getElementsByClass("myui-vodlist__box")
            for(e in elements){
                val a=e.child(0)
                val title=a.attr("title")
                val href=a.attr("href")
                val data_original=a.attr("data-original")
                val update=a.select("span[class=pic-text text-right]").text()
                val tag_top=a.select("span[class=pic-tag pic-tag-top]")[0]
                val score=tag_top.child(0).text()
                val year=tag_top.child(1).text()
                val d=e.child(1)
                val describe=d.select("p").text()

                val b= ComicListBean.ComicBean(title,href,data_original,update,score,year,describe)
                data.add(b)

            }
            val bean=ComicListBean()
            bean.data=data
            it.onNext(bean)
            it.onComplete()

        }


    }



}